package http

import (
	"crypto/tls"
	"log"
	"net/http"
	"proxy/config"
)

func Serve() {
	addr := config.GetListenAddr()
	server := &http.Server{
		Addr:         addr,
		TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler)),
		Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			auth := config.GetAuthorization()
			authHeader := r.Header.Get("proxy-authorization")
			if auth != "" && auth != authHeader {
				log.Printf("Request proxy-authorization error: %s\n", authHeader)
				http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
				return
			}

			HttpProxy(w, r)
		}),
	}
	log.Printf("Https服务器启动：%s\n", addr)
	log.Fatal(server.ListenAndServeTLS(config.Config.CertFile, config.Config.KeyFile))
}
